import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author gorkr
 * @date 2022/07/12 22:22
 **/
public class Counter {

    private final int failureCount;

    private final long failureTimeInterval;

    private final AtomicInteger currentCount;

    // 上一次调用失败的时间戳
    private long lastTime;

    private final AtomicInteger halfOpenSuccessCount;

    public Counter(int failureCount, long failureTimeInterval){
        this.failureCount = failureCount;
        this.failureTimeInterval = failureTimeInterval;
        this.currentCount = new AtomicInteger(0);
        this.halfOpenSuccessCount = new AtomicInteger(0);
        this.lastTime = System.currentTimeMillis();
    }

    // todo: 弄清楚在哪里增加了失败次数
    public synchronized int incrFailureCount(){
        long current = System.currentTimeMillis();
        if(current - lastTime > failureTimeInterval){
            // 超过时间窗口， 当前失败次数重置为0
            lastTime = current;
            currentCount.set(0);
        }
        return currentCount.getAndIncrement();
    }

    public int incrSuccessHalfOpenCount(){
        return this.halfOpenSuccessCount.incrementAndGet();
    }

    // 失败次数是否达到阈值
    public boolean failureThresholdReached(){
        return getCurCount() >= failureCount;
    }

    public int getCurCount(){
        return currentCount.get();
    }

    public synchronized void reset(){
        halfOpenSuccessCount.set(0);
        currentCount.set(0);
    }




}
    